package com.ics.atable.chat.controller;

import com.ics.atable.chat.model.dto.DbConfigDTO;
import com.ics.atable.chat.service.DbConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据库配置管理控制器
 * 
 * 提供REST API接口来管理数据库配置
 * 支持增删改查、启用禁用、连接测试等功能
 * 
 * @author Chawu
 */
@Slf4j
@RestController
@RequestMapping("/api/db-config")
@Tag(name = "数据库配置管理", description = "数据库配置管理相关接口")
@Validated
public class DbConfigController {
    
    @Autowired
    private DbConfigService dbConfigService;
    
    /**
     * 添加数据库配置
     * 
     * @param dto 配置DTO
     * @return 操作结果
     */
    @PostMapping
    @Operation(summary = "添加数据库配置", description = "添加新的数据库配置")
    public ResponseEntity<Map<String, Object>> addDbConfig(
            @Parameter(description = "数据库配置信息") 
            @Valid @RequestBody DbConfigDTO dto) {
        
        log.info("收到添加数据库配置请求: {}", dto.getName());
        
        try {
            boolean success = dbConfigService.addDbConfig(dto);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", success);
            result.put("message", success ? "添加成功" : "添加失败");
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("添加数据库配置失败: {}", e.getMessage(), e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "添加失败: " + e.getMessage());
            
            return ResponseEntity.badRequest().body(result);
        }
    }
    
    /**
     * 更新数据库配置
     * 
     * @param id 配置ID
     * @param dto 配置DTO
     * @return 操作结果
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新数据库配置", description = "更新指定的数据库配置")
    public ResponseEntity<Map<String, Object>> updateDbConfig(
            @Parameter(description = "配置ID") 
            @PathVariable Long id,
            
            @Parameter(description = "数据库配置信息") 
            @Valid @RequestBody DbConfigDTO dto) {
        
        log.info("收到更新数据库配置请求: ID={}, Name={}", id, dto.getName());
        
        try {
            dto.setId(id);
            boolean success = dbConfigService.updateDbConfig(dto);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", success);
            result.put("message", success ? "更新成功" : "更新失败");
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("更新数据库配置失败: {}", e.getMessage(), e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "更新失败: " + e.getMessage());
            
            return ResponseEntity.badRequest().body(result);
        }
    }
    
    /**
     * 删除数据库配置
     * 
     * @param id 配置ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除数据库配置", description = "删除指定的数据库配置")
    public ResponseEntity<Map<String, Object>> deleteDbConfig(
            @Parameter(description = "配置ID") 
            @PathVariable Long id) {
        
        log.info("收到删除数据库配置请求: ID={}", id);
        
        try {
            boolean success = dbConfigService.deleteDbConfig(id);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", success);
            result.put("message", success ? "删除成功" : "删除失败");
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("删除数据库配置失败: {}", e.getMessage(), e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "删除失败: " + e.getMessage());
            
            return ResponseEntity.badRequest().body(result);
        }
    }
    
    /**
     * 根据ID查询配置
     * 
     * @param id 配置ID
     * @return 配置信息
     */
    @GetMapping("/{id}")
    @Operation(summary = "查询数据库配置", description = "根据ID查询数据库配置")
    public ResponseEntity<DbConfigDTO> getDbConfigById(
            @Parameter(description = "配置ID") 
            @PathVariable Long id) {
        
        log.info("收到查询数据库配置请求: ID={}", id);
        
        try {
            DbConfigDTO dto = dbConfigService.getDbConfigById(id);
            
            if (dto != null) {
                return ResponseEntity.ok(dto);
            } else {
                return ResponseEntity.notFound().build();
            }
            
        } catch (Exception e) {
            log.error("查询数据库配置失败: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 根据名称查询配置
     * 
     * @param name 配置名称
     * @return 配置信息
     */
    @GetMapping("/name/{name}")
    @Operation(summary = "根据名称查询配置", description = "根据数据源名称查询配置")
    public ResponseEntity<DbConfigDTO> getDbConfigByName(
            @Parameter(description = "配置名称") 
            @PathVariable String name) {
        
        log.info("收到根据名称查询配置请求: Name={}", name);
        
        try {
            DbConfigDTO dto = dbConfigService.getDbConfigByName(name);
            
            if (dto != null) {
                return ResponseEntity.ok(dto);
            } else {
                return ResponseEntity.notFound().build();
            }
            
        } catch (Exception e) {
            log.error("根据名称查询配置失败: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 查询所有配置
     * 
     * @return 配置列表
     */
    @GetMapping
    @Operation(summary = "查询所有配置", description = "查询所有数据库配置")
    public ResponseEntity<List<DbConfigDTO>> getAllDbConfigs() {
        
        log.info("收到查询所有配置请求");
        
        try {
            List<DbConfigDTO> configs = dbConfigService.getAllDbConfigs();
            return ResponseEntity.ok(configs);
            
        } catch (Exception e) {
            log.error("查询所有配置失败: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 查询启用的配置
     * 
     * @return 启用的配置列表
     */
    @GetMapping("/enabled")
    @Operation(summary = "查询启用的配置", description = "查询所有启用的数据库配置")
    public ResponseEntity<List<DbConfigDTO>> getEnabledDbConfigs() {
        
        log.info("收到查询启用配置请求");
        
        try {
            List<DbConfigDTO> configs = dbConfigService.getEnabledDbConfigs();
            return ResponseEntity.ok(configs);
            
        } catch (Exception e) {
            log.error("查询启用配置失败: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 启用/禁用配置
     * 
     * @param id 配置ID
     * @param enabled 启用状态
     * @return 操作结果
     */
    @PutMapping("/{id}/enabled")
    @Operation(summary = "启用/禁用配置", description = "启用或禁用指定的数据库配置")
    public ResponseEntity<Map<String, Object>> updateEnabled(
            @Parameter(description = "配置ID") 
            @PathVariable Long id,
            
            @Parameter(description = "启用状态") 
            @RequestParam Boolean enabled) {
        
        log.info("收到更新启用状态请求: ID={}, Enabled={}", id, enabled);
        
        try {
            boolean success = dbConfigService.updateEnabled(id, enabled);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", success);
            result.put("message", success ? "更新成功" : "更新失败");
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("更新启用状态失败: {}", e.getMessage(), e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "更新失败: " + e.getMessage());
            
            return ResponseEntity.badRequest().body(result);
        }
    }
    
    /**
     * 测试数据源连接
     * 
     * @param dto 配置DTO
     * @return 测试结果
     */
    @PostMapping("/test-connection")
    @Operation(summary = "测试数据源连接", description = "测试数据库配置的连接是否正常")
    public ResponseEntity<Map<String, Object>> testConnection(
            @Parameter(description = "数据库配置信息") 
            @Valid @RequestBody DbConfigDTO dto) {
        
        log.info("收到测试连接请求: {}", dto.getName());
        
        try {
            boolean connected = dbConfigService.testConnection(dto);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", connected);
            result.put("message", connected ? "连接测试成功" : "连接测试失败");
            result.put("connected", connected);
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("测试连接失败: {}", e.getMessage(), e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "测试连接失败: " + e.getMessage());
            result.put("connected", false);
            
            return ResponseEntity.badRequest().body(result);
        }
    }
}
